package com.pmcc.core.service;

import com.pmcc.core.entity.Dict;
import com.pmcc.core.repository.DictRepository;
import com.pmcc.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

/**
 * Created by chenqf on 2017/12/14.
 */
@Service
@Transactional
public class DictService {
    @Autowired
    DictRepository dictRepository;

    public ResultBean queryByPage(AntdPage antdPage, Dict model){
        ResultBean resultBean =new ResultBean(ResultBean.SUCCESS);
        try {
            Page page = dictRepository.findAll(this.getSpecification(model), antdPage.getPageRequest());
            resultBean.setPage(antdPage.getDefaultCurrent());
            resultBean.setTotal(page.getTotalElements());
            resultBean.setPageSize(antdPage.getPageSize());
            resultBean.setRows(page.getContent());
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public Specification<Dict> getSpecification(Dict dict) {
        return new Specification<Dict>() {
            @Override
            public Predicate toPredicate(Root<Dict> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                List<Predicate> list = new ArrayList<Predicate>();
                list.add(builder.equal(root.get("parentId").as(String.class),  dict.getParentId()));
                //编码
                if (StringUtil.isNotEmpty(dict.getCode())) {
                    list.add(builder.like(root.get("code").as(String.class),  "%"+dict.getCode().trim()+"%"));
                }
                //名称
                if(StringUtil.isNotEmpty(dict.getName())){
                    list.add(builder.like(root.get("name").as(String.class),  "%"+dict.getName().trim()+"%"));
                }
                Predicate[] p = new Predicate[list.size()];
                return builder.and(list.toArray(p));
            }
        };
    }
    public ResultBean addDict(Dict dict) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            //处理默认信息
            dict.setDelFlag("0");
            dict.setParentId("root");
            //排序
            List<Dict> dictList = dictRepository.findByParentIdAndDelFlagOrderBySequenceAsc("root", "0");
            if(dictList.size()==0){
                dict.setSequence(1);
            }else{
                dict.setSequence(dictList.get(dictList.size()-1).getSequence()+1);
            }
            //保存主信息
            dict=dictRepository.saveAndFlush(dict);
            //保存明细信息
            this.saveDetail(dict.getId(),dict.getDetail());
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    /**
     * 保存明细
     * @param parentId
     * @param list
     */
    public void saveDetail(String parentId,List<Map<String,String>> list)throws Exception{
        for (Map<String,String> map : list){
            if("0".equals(map.get("delFlag"))) {
                Dict dict = new Dict();
                if (StringUtil.isEmpty(map.get("id"))) {
                    dict = new Dict();
                } else {
                    dict = dictRepository.findOne(map.get("id"));
                }
                dict.setDelFlag(map.get("delFlag"));
                dict.setCode(map.get("code"));
                dict.setName(map.get("name"));
                dict.setParentId(parentId);
                dict.setSequence(1);
                dict.setRemark(map.get("remark"));
//                dict.setStatus("Y");
                dictRepository.save(dict);
            }else{
                Dict d = dictRepository.findOne(map.get("id"));
                if(d!=null){
                    dictRepository.delete(map.get("id"));
                }
            }
        }
    }

    public ResultBean queryById(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            Map map = new HashMap();
            Dict dict = dictRepository.findOne(id);
            List<Dict> dictList = dictRepository.findByParentIdAndDelFlagOrderBySequenceAsc(id, "0");
            for (Dict d: dictList) {
                d.setKey(d.getId());
            }
            map.put("dict",dict);
            map.put("detail",dictList);
            resultBean.setObject(map);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean editDict(Map map) {
        ResultBean resultBean =new ResultBean(ResultBean.SUCCESS);
        try {
            Dict dictOld = dictRepository.findOne(map.get("id").toString());
            dictOld.setName(map.get("name").toString());
            dictOld.setCode(map.get("code").toString());
            dictOld.setRemark(map.get("remark").toString());
            dictRepository.saveAndFlush(dictOld);
            //保存明细信息
            this.saveDetail(dictOld.getId(),(List<Map<String,String>>) map.get("detail"));
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean deleteDict(String id) {
        ResultBean resultBean =new ResultBean(ResultBean.SUCCESS);
        try {
            dictRepository.deleteByParentId(id);
            dictRepository.delete(id);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean queryCode(String code) {
        ResultBean resultBean = new ResultBean();
        try{
            List<Dict> list = dictRepository.findByCode(code);
            if(list.size()==1){
                resultBean.setResultCode(ResultBean.SUCCESS);
            }
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean queryDictByCode(String code) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            List<Dict> list=dictRepository.findByCode(code);
            if(list != null && list.size()>0){
                resultBean.setRows(dictRepository.findByParentIdAndDelFlagOrderBySequenceAsc(list.get(0).getId(),"0"));
            }
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
}
